import { ConfigEnv, UserConfig, loadEnv } from 'vite';
import { viteMockServe } from 'vite-plugin-mock';
import createVuePlugin from '@vitejs/plugin-vue';
import vueJsx from '@vitejs/plugin-vue-jsx';
import svgLoader from 'vite-svg-loader';

// @ts-ignore
import path, { resolve } from 'path';

const CWD = process.cwd();

function pathResolve(dir: string) {
  return resolve(process.cwd(), '.', dir);
}

export default ({ mode }: ConfigEnv): UserConfig => {
  const { VITE_WEB_BASE_PATH, VITE_SERVER_BASE_URL, VITE_APP_PORT, VITE_PROXY_SERVER } = loadEnv(
    mode,
    CWD,
  );
  const apiRouteReg = new RegExp(`^${VITE_SERVER_BASE_URL}`);
  // 代理配置
  const proxy = {
    [VITE_SERVER_BASE_URL]: {
      target: VITE_PROXY_SERVER,
      changeOrigin: true,
      ws: true,
      rewrite: (path: string) => path.replace(apiRouteReg, ''),
    },
  };

  return {
    base: VITE_WEB_BASE_PATH,
    resolve: {
      alias: [
        {
          find: /@\//,
          replacement: `${pathResolve('src')}/`,
        },
      ],
    },
    css: {
      preprocessorOptions: {
        less: {
          modifyVars: {
            hack: `true; @import (reference) "${path.resolve('src/style/variables.less')}";`,
          },
          math: 'strict',
          javascriptEnabled: true,
        },
      },
    },

    plugins: [
      createVuePlugin(),
      vueJsx(),
      viteMockServe({
        mockPath: 'mock',
        localEnabled: true,
      }),
      svgLoader(),
    ],
    // optimizeDeps: {
    //   include: [
    //     `monaco-editor/esm/vs/language/json/json.worker`,
    //     `monaco-editor/esm/vs/language/html/html.worker`,
    //     `monaco-editor/esm/vs/language/css/css.worker`,
    //     `monaco-editor/esm/vs/language/typescript/ts.worker`,
    //     `monaco-editor/esm/vs/editor/editor.worker`,
    //   ],
    // },
    server: {
      host: '0.0.0.0',
      // @ts-ignore
      port: VITE_APP_PORT ?? 3000,
      // 代理配置
      proxy,
    },
  };
};
